package com.kai.demo.security;

import com.kai.demo.entity.Menu;
import com.kai.demo.entity.Role;
import com.kai.demo.entity.User;
import com.kai.demo.mapper.UserMapper;
import com.kai.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>Project: sprigncloud-demo </p>
 * <p>Description: </p>
 * <p>Copyright (c) 2024 Karrytech (Shanghai/Beijing) Co., Ltd.</p>
 * <p>All Rights Reserved.</p>
 *
 * @author <a href="mailto:zhangkai@karrytech.com">Zhang Kai</a>
 */
@Service
public class SecurityUserDetailService implements UserDetailsService {

    @Resource
    private UserService userService;
    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getByName(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }

        List<GrantedAuthority> auths = new ArrayList<>();
        //查询用户角色列表
        List<Role> roles = userMapper.selectRoleByUserId(user.getId());
        //查询用户权限列表
        List<Menu> menus = userMapper.selectMenuByUserId(user.getId());

        //处理角色  拼接   ROLE_xxx
        for (Role role : roles) {
            auths.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
        }
        //处理权限
        for (Menu menu : menus) {
            auths.add(new SimpleGrantedAuthority(menu.getPermission()));
        }

        BCryptPasswordEncoder cryptPasswordEncoder = new BCryptPasswordEncoder();
        return new org.springframework.security.core.userdetails.User(user.getName(), cryptPasswordEncoder.encode(user.getPassword()), auths);
    }
}